package fr.labri.harmony.analysis.jsep.results.filter;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import fr.labri.harmony.analysis.jsep.results.LoadRules;
import fr.labri.harmony.analysis.jsep.results.ProjectActivity;

public class CorpusMigrantsStatsSummary extends ResultFilter {

	/*
	 * Compute the stats of the project when they performed a migration (end of the segment)
	 */
	@Override
	public void computeResult(ResultSet rs) throws SQLException, IOException {

		Set<String> migrants = new HashSet<String>();
		Map<String,List<DataProject>> corpus = new HashMap<>();
		rs.first();
		while (rs.next()){		
			String source = rs.getString("NAME");
			String target = rs.getString("MIGRATION_LIB_TO");
			if(LoadRules.isTrueRule(source, target)) {
				migrants.add(rs.getString("PROJECT"));
				String project = rs.getString("PROJECT");
				int cloc = rs.getInt("SIZE_OUT");
				int nblibs = rs.getInt("LIBS_OUT");
				long timestamp = rs.getLong("TIMESTAMP_OUT");
				int nbmonths = ProjectActivity.getMonthsForProject(project, timestamp);
				int commits = rs.getInt("INTRO_OUT_NUMBER");
				int nbdev = rs.getInt("NB_DEV_OUT");
				if(!corpus.containsKey(project)) corpus.put(project, new ArrayList<DataProject>());		
				corpus.get(project).add(new DataProject(commits, cloc, nblibs, nbmonths, nbdev, ProjectActivity.getStart(project), timestamp));
			}
		}
		PrintStream ps = new PrintStream(System.out);
		ps.println("Nombre de projets migrants "+migrants.size());
		ps = new PrintStream(new FileOutputStream("corpus_migrants_stats.csv"));
		ps.println("PROJECT,MIGRATION_VERSION_NUMBER,MIGRATION_CLOC,MIGRATION_LIBS,MIGRATION_MONTHS,MIGRATION_DEVS,START_PROJECT,TIMESTAMP_OUT");
		for(String project : corpus.keySet()) 
			for(DataProject dp : corpus.get(project))
				ps.println(project+","+dp);
		ps.close();


	}

	class DataProject {
		public DataProject(int commits, int cloc, int nblibs, int nbmonths, int nbdev, long start_project, long timestamp_out) {
			super();
			this.commits = commits;
			this.cloc = cloc;
			this.nblibs = nblibs;
			this.nbmonths = nbmonths;
			this.nbdev = nbdev;
			this.start_project = start_project;
			this.timestamp_out = timestamp_out;
		}
		int commits;
		int cloc;
		int nblibs;
		int nbmonths;
		int nbdev;
		long start_project;
		long timestamp_out;

		@Override
		public String toString() {
			return commits+","+cloc+","+nblibs+","+nbmonths+","+nbdev+","+start_project+","+timestamp_out;
		}
	}
}
